import axios from 'axios';
import { Loading, Message } from 'element-ui';

//自定义创建axios对象
const selfAxios = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    // baseURL: '/',
    timeout: 5000 // 请求超时 5000毫秒
});

const loading = {
    //loading实例
    loadingInstance: null,
    //打开加载
    open() {
        if (!this.loadingInstance) {
            this.loadingInstance = Loading.service({ target: '.main', text: '拼死加载中...' });
        }
    },
    //关闭加载
    close() {
        if (this.loadingInstance) {
            this.loadingInstance.close();
            this.loadingInstance = null;
        }


    }
}


//请求拦截器
selfAxios.interceptors.request.use(config => {
    //发送请求和接受响应让它处于加载
    loading.open();
    return config
}, error => {
    //出现异常
    loading.open();
    return Promise.reject(error)
});
// 响应拦截器
selfAxios.interceptors.response.use(response => {
    //接受完响应数据 就停止加载
    loading.close();

    //如果后台响应的状态不是2000 说明后台处理异常
    if (response.data.code !== 2000) {
        Message({
            message: response.data.message || '系统异常',
            type: 'warning',
            duration: 5000
        });
    }
    return response
}, error => {
    loading.close();

    Message({
        message: error.message,
        type: 'error',
        duration: 4000
    });
    return Promise.reject(error);
})

// selfAxios.get('/db.json').then(response => {
//     console.log(response.data);
// });

export default selfAxios; //导出自定义创建axios对象